<template>
  <div class="visit-ranking-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="统计周期">
          <el-select v-model="filterForm.period" placeholder="请选择统计周期">
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
            <el-option label="本季度" value="quarter" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="filterForm.period === 'custom'" label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="分公司">
          <el-select v-model="filterForm.companyId" placeholder="请选择分公司" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上门类型">
          <el-select v-model="filterForm.visitType" placeholder="请选择上门类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="首次上门" value="first" />
            <el-option label="回访" value="return" />
            <el-option label="签约上门" value="contract" />
            <el-option label="售后服务" value="service" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon total">
              <el-icon><Position /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.totalVisits }}</div>
              <div class="stats-label">总上门次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon success">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.successVisits }}</div>
              <div class="stats-label">成功上门</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon rate">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ (statsData.successRate * 100).toFixed(1) }}%</div>
              <div class="stats-label">成功率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon avg">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.avgVisitsPerDay }}</div>
              <div class="stats-label">日均上门</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表分析 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>上门趋势分析</span>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>上门类型分布</span>
          </template>
          <div ref="typeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 排行榜表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>上门排行榜</span>
          <div class="header-actions">
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出排行榜
            </el-button>
            <el-button type="primary" size="small" @click="handleViewMap">
              <el-icon><Location /></el-icon>
              地图查看
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column label="排名" width="80" align="center">
          <template #default="{ $index }">
            <div class="rank-cell">
              <el-icon v-if="$index < 3" class="rank-icon" :class="getRankIconClass($index)">
                <Medal />
              </el-icon>
              <span v-else class="rank-number">{{ $index + 1 }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="业务员" width="150">
          <template #default="{ row }">
            <div class="salesman-cell">
              <el-avatar :size="32" :src="row.avatar">
                {{ row.salesmanName?.charAt(0) }}
              </el-avatar>
              <span class="salesman-name">{{ row.salesmanName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="companyName" label="分公司" width="120" />
        <el-table-column prop="totalVisits" label="总上门次数" width="120" align="center">
          <template #default="{ row }">
            <span class="visit-count">{{ row.totalVisits }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="successVisits" label="成功上门" width="100" align="center">
          <template #default="{ row }">
            <span class="success-count">{{ row.successVisits }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="successRate" label="成功率" width="100" align="center">
          <template #default="{ row }">
            <span :class="getSuccessRateClass(row.successRate)">
              {{ (row.successRate * 100).toFixed(1) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="avgDistance" label="平均距离(km)" width="120" align="center">
          <template #default="{ row }">
            {{ row.avgDistance?.toFixed(1) || '0.0' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalDistance" label="总里程(km)" width="120" align="center">
          <template #default="{ row }">
            {{ row.totalDistance?.toFixed(1) || '0.0' }}
          </template>
        </el-table-column>
        <el-table-column prop="visitTypes" label="上门类型" width="200">
          <template #default="{ row }">
            <div class="visit-types">
              <el-tag
                v-for="type in row.visitTypes"
                :key="type.type"
                :type="getVisitTypeTag(type.type)"
                size="small"
                class="type-tag"
              >
                {{ getVisitTypeName(type.type) }}({{ type.count }})
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lastVisitDate" label="最近上门" width="120" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="success" size="small" @click="handleViewTrack(row)">
              轨迹
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Download, 
  Location, 
  Position, 
  CircleCheck, 
  TrendCharts, 
  DataAnalysis,
  Medal
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const trendChartRef = ref<HTMLDivElement>()
const typeChartRef = ref<HTMLDivElement>()

// 筛选表单
const filterForm = reactive({
  period: 'month',
  dateRange: [],
  companyId: '',
  visitType: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 统计数据
const statsData = reactive({
  totalVisits: 0,
  successVisits: 0,
  successRate: 0,
  avgVisitsPerDay: 0
})

// 表格数据
const tableData = ref([])

// 下拉选项
const companyList = ref([])

// 图表实例
let trendChart: echarts.ECharts | null = null
let typeChart: echarts.ECharts | null = null

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
  updateCharts()
}

const handleReset = () => {
  Object.assign(filterForm, {
    period: 'month',
    dateRange: [],
    companyId: '',
    visitType: ''
  })
  handleFilter()
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleViewMap = () => {
  ElMessage.info('地图查看功能开发中')
}

const handleViewDetail = (row: any) => {
  ElMessage.info(`查看 ${row.salesmanName} 的上门详情`)
}

const handleViewTrack = (row: any) => {
  ElMessage.info(`查看 ${row.salesmanName} 的上门轨迹`)
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          salesmanName: '张三',
          companyName: '北京分公司',
          totalVisits: 85,
          successVisits: 68,
          successRate: 0.8,
          avgDistance: 12.5,
          totalDistance: 1062.5,
          visitTypes: [
            { type: 'first', count: 25 },
            { type: 'return', count: 35 },
            { type: 'contract', count: 15 },
            { type: 'service', count: 10 }
          ],
          lastVisitDate: '2025-08-15',
          avatar: ''
        },
        {
          salesmanName: '李四',
          companyName: '上海分公司',
          totalVisits: 72,
          successVisits: 58,
          successRate: 0.806,
          avgDistance: 8.3,
          totalDistance: 597.6,
          visitTypes: [
            { type: 'first', count: 20 },
            { type: 'return', count: 30 },
            { type: 'contract', count: 12 },
            { type: 'service', count: 10 }
          ],
          lastVisitDate: '2024-01-14',
          avatar: ''
        }
      ]
      pagination.total = 120
      
      // 更新统计数据
      Object.assign(statsData, {
        totalVisits: 2580,
        successVisits: 2064,
        successRate: 0.8,
        avgVisitsPerDay: 83
      })
      
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const initCharts = () => {
  nextTick(() => {
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value)
    }
    if (typeChartRef.value) {
      typeChart = echarts.init(typeChartRef.value)
    }
    updateCharts()
  })
}

const updateCharts = () => {
  updateTrendChart()
  updateTypeChart()
}

const updateTrendChart = () => {
  if (!trendChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总上门', '成功上门']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      name: '上门次数'
    },
    series: [
      {
        name: '总上门',
        type: 'line',
        data: [45, 52, 48, 61, 55, 38, 42],
        smooth: true,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '成功上门',
        type: 'line',
        data: [36, 42, 38, 49, 44, 30, 34],
        smooth: true,
        itemStyle: { color: '#67c23a' }
      }
    ]
  }
  trendChart.setOption(option)
}

const updateTypeChart = () => {
  if (!typeChart) return
  
  const data = [
    { name: '首次上门', value: 680 },
    { name: '回访', value: 920 },
    { name: '签约上门', value: 520 },
    { name: '售后服务', value: 460 }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}次 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '上门类型',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  typeChart.setOption(option)
}

// 工具方法
const getRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex === 0) return 'first-place-row'
  if (rowIndex === 1) return 'second-place-row'
  if (rowIndex === 2) return 'third-place-row'
  return ''
}

const getRankIconClass = (index: number) => {
  const classes = ['gold-medal', 'silver-medal', 'bronze-medal']
  return classes[index] || ''
}

const getSuccessRateClass = (rate: number) => {
  if (rate >= 0.8) return 'high-rate'
  if (rate >= 0.6) return 'medium-rate'
  return 'low-rate'
}

const getVisitTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    first: 'primary',
    return: 'success',
    contract: 'warning',
    service: 'info'
  }
  return tagMap[type] || 'info'
}

const getVisitTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    first: '首次',
    return: '回访',
    contract: '签约',
    service: '服务'
  }
  return nameMap[type] || type
}

// 初始化数据
const initData = () => {
  companyList.value = [
    { id: '1', name: '北京分公司' },
    { id: '2', name: '上海分公司' },
    { id: '3', name: '广州分公司' },
    { id: '4', name: '深圳分公司' },
    { id: '5', name: '杭州分公司' }
  ]
  
  getTableData()
  initCharts()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.visit-ranking-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .stats-row {
    margin-bottom: 20px;
    
    .stats-card {
      .stats-item {
        display: flex;
        align-items: center;
        
        .stats-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          font-size: 24px;
          color: white;
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.success {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.rate {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.avg {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }
        
        .stats-content {
          .stats-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }
          
          .stats-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .rank-cell {
      display: flex;
      align-items: center;
      justify-content: center;
      
      .rank-icon {
        font-size: 24px;
        
        &.gold-medal {
          color: #ffd700;
        }
        
        &.silver-medal {
          color: #c0c0c0;
        }
        
        &.bronze-medal {
          color: #cd7f32;
        }
      }
      
      .rank-number {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .salesman-cell {
      display: flex;
      align-items: center;
      
      .salesman-name {
        margin-left: 10px;
      }
    }
    
    .visit-count {
      color: #409eff;
      font-weight: bold;
    }
    
    .success-count {
      color: #67c23a;
      font-weight: bold;
    }
    
    .high-rate {
      color: #67c23a;
      font-weight: bold;
    }
    
    .medium-rate {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .low-rate {
      color: #f56c6c;
      font-weight: bold;
    }
    
    .visit-types {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
      
      .type-tag {
        margin: 0;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}

// 表格行样式
:deep(.first-place-row) {
  background-color: rgba(255, 215, 0, 0.1) !important;
}

:deep(.second-place-row) {
  background-color: rgba(192, 192, 192, 0.1) !important;
}

:deep(.third-place-row) {
  background-color: rgba(205, 127, 50, 0.1) !important;
}
</style>
